package com.api.shopapi.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.api.shopapi.common.HttpClientUtil;
import com.api.shopapi.entity.*;
import com.api.shopapi.entity.dto.DeviceLXXueYaJiDTO;
import com.api.shopapi.service.*;
import com.github.pagehelper.PageInfo;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

//废弃

@RestController
@RequestMapping("LeXinXueYaJi")
public class LeXinXueYaJiController extends BaseController {

    @Autowired
    @Qualifier("DeviceLXXueYaJiServiceImplOne")
    private DeviceLXXueYaJiService deviceLXXueYaJiService;

    @Autowired
    @Qualifier("UserServiceImplOne")
    private UserService userService;

    @Autowired
    @Qualifier("UserDeviceServiceImplOne")
    private UserDeviceService userDeviceService;

    @Autowired
    @Qualifier("LXXueYaJiServiceImplOne")
    private LXXueYaJiService lxXueYaJiService;

    @Autowired
    @Qualifier("JKXueyaServiceImplOne")
    private JKXueyaService jkXueyaService;


    //查询设备 返回设备id
    public String QueryingDevice(String value, String keytype) {
        String path1 = "http://open.lifesense.com/openapi_service/device/api/getDeviceinfo?";
        String appid = "8371455a6f413662894ba8c5eebe7def39a87003";
        String APPsecret = "173dbe8941ccf6314e5842644ba76c0caa4896f3";
        long timestamp = System.currentTimeMillis();
        String nonce = "A1B12233";
        String checksum = SHA1(appid + APPsecret + timestamp + nonce);
        String path = path1 + "appid=" + appid + "&timestamp=" + timestamp + "&nonce=" + nonce + "&checksum=" + checksum;
//        String paramsJson = "{\"keytype\":\"" + keytype + "\",\"value\":\"" + value + "\" }";
//        HttpClientUtil httpClientUtil = new HttpClientUtil();
//        return httpClientUtil.sendHttpPostJson(path, paramsJson);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("keytype", keytype);
        hashMap.put("value", value);
        return postTemplate(path, hashMap);
    }


    //绑定设备
    public String BindingDevice(String deviceId, String userNo, String mobile) {
        String path1 = "http://open.lifesense.com/openapi_service/device/api/bindDevice?";
        long timestamp = System.currentTimeMillis();
        String appid = "8371455a6f413662894ba8c5eebe7def39a87003";
        String APPsecret = "173dbe8941ccf6314e5842644ba76c0caa4896f3";
        String nonce = "A1B12233";
        String checksum = SHA1(appid + APPsecret + timestamp + nonce);
        String path = path1 + "appid=" + appid + "&timestamp=" + timestamp + "&nonce=" + nonce + "&checksum=" + checksum;
//        String paramsJson = "{\"deviceId\":\"" + deviceId + "\",\"userNo\":\"" + userNo + "\",\"mobile\":\"" + mobile + "\" }";
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("deviceId", deviceId);
        hashMap.put("userNo", userNo);
        hashMap.put("mobile", mobile);
        return postTemplate(path, hashMap);
        //        HttpClientUtil httpClientUtil = new HttpClientUtil();
//        return httpClientUtil.sendHttpPostJson(path, paramsJson);
    }

    //解绑设备
    public String removeDevice(String deviceId, int userNo) {
        String APPsecret = "173dbe8941ccf6314e5842644ba76c0caa4896f3";
        String path1 = "http://open.lifesense.com/openapi_service/device/api/ubindDevice?";
        String appid = "8371455a6f413662894ba8c5eebe7def39a87003";
        long timestamp = System.currentTimeMillis();
        String nonce = "A1B12233";
        String checksum = SHA1(appid + APPsecret + timestamp + nonce);
        String path = path1 + "appid=" + appid + "&timestamp=" + timestamp + "&nonce=" + nonce + "&checksum=" + checksum;
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("deviceId", deviceId);
        hashMap.put("userNo", userNo);
        return postTemplate(path, hashMap);
//        String paramsJson = "{\"deviceId\":\"" + deviceId + "\",\"userNo\":\"" + userNo + "\"}";
//        HttpClientUtil httpClientUtil = new HttpClientUtil();
//        return httpClientUtil.sendHttpPostJson(path, paramsJson);
    }


    //查询设备 返回设备id
    @RequestMapping(value = "QueryingDeviceId", method = RequestMethod.POST)
    public MyResult QueryingDeviceId(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
//            String staffCode = jsonObject.getString("staffCode");
            String value = jsonObject.getString("value");
//            if(!checkSignPC(timeStr,sign)){
//                return failed("签名错误");
//            }
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/LeXinXueYaJi/QueryingDeviceId");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            String result = QueryingDevice(value.trim(), "sn");
            JSONObject jsonObject1 = JSON.parseObject(result);
            int code = jsonObject1.getInteger("code");
            if (code == 200) {
                return success(jsonObject1);
            } else {
                return failed(jsonObject1.getString("msg"));
            }
        } catch (Exception e) {
            insertError("/LeXinXueYaJi/QueryingDeviceId", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //绑定设备
    @RequestMapping(value = "BindDevice", method = RequestMethod.POST)
    @Transactional
    public MyResult BindDevice(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
//            String staffCode = jsonObject.getString("staffCode");
            String userCode = jsonObject.getString("userCode");
            String deviceId = jsonObject.getString("deviceId");
            String sn = jsonObject.getString("sn");

//            if(!checkSignPC(timeStr,sign)){
//                return failed("签名错误");
//            }
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/LeXinXueYaJi/BindDevice");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            User user = userService.getByUserCode(userCode);
            if (user == null) {
                return failed("该用户不存在!");
            }
            DeviceLXXueYaJi deviceLXXueYaJi = deviceLXXueYaJiService.getBySN(sn);
            if (deviceLXXueYaJi != null) {
                if (!deviceLXXueYaJi.getUserCode().equals(userCode)) {
                    return failed("该设备已被绑定！");
                }
            }
            String result = BindingDevice(deviceId, "", user.getPhone());
            JSONObject jsonObject1 = JSON.parseObject(result);
            int code = jsonObject1.getInteger("code");
            if (code == 200) {
                DeviceLXXueYaJi deviceLXXueYaJi1 = deviceLXXueYaJiService.getByUserCode(userCode);
                if (deviceLXXueYaJi1 == null) {
                    DeviceLXXueYaJi deviceLXXueYaJi2 = new DeviceLXXueYaJi();
                    deviceLXXueYaJi2.setDeviceLXXueYaJiCode(UUID.randomUUID().toString());
                    deviceLXXueYaJi2.setUserCode(userCode);
                    deviceLXXueYaJi2.setSN(sn);
                    deviceLXXueYaJi2.setDeviceId(deviceId);
                    deviceLXXueYaJi2.setBindTime(new Date());
                    deviceLXXueYaJiService.insert(deviceLXXueYaJi2);
                } else {
                    deviceLXXueYaJi1.setSN(sn);
                    deviceLXXueYaJi1.setDeviceId(deviceId);
                    deviceLXXueYaJi1.setBindTime(new Date());
                    deviceLXXueYaJiService.update(deviceLXXueYaJi1);
                }
                UserDevice userDevice = userDeviceService.getByUserCode(userCode);
                if (userDevice == null) {
                    UserDevice userDevice1 = new UserDevice();
                    userDevice1.setUserDeviceCode(UUID.randomUUID().toString());
                    userDevice1.setUserCode(userCode);
                    userDevice1.setLXXueYaJi(1);
                    userDeviceService.insert(userDevice1);
                } else {
                    userDevice.setLXXueYaJi(1);
                    userDeviceService.update(userDevice);
                }
                return success(jsonObject1);
            } else {
                return failed(jsonObject1.getString("msg"));
            }
        } catch (Exception e) {
            insertErrorForAffair("/LeXinXueYaJi/BindDevice!", jsonObject, e);
            return anomalous(getExceptionMsg(e));
        }
    }

    //解绑设备
    @RequestMapping(value = "RemoveDevice", method = RequestMethod.POST)
    @Transactional
    public MyResult RemoveDevice(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
//            String staffCode = jsonObject.getString("staffCode");
            String userCode = jsonObject.getString("userCode");
//            if (!checkSignPC(timeStr, sign)) {
//                return failed("签名错误");
//            }
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/LeXinXueYaJi/RemoveDevice");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            DeviceLXXueYaJi deviceLXXueYaJi = deviceLXXueYaJiService.getByUserCode(userCode);
            if (deviceLXXueYaJi == null) {
                return failed("该用户没有绑定此设备!");
            } else {
                if (deviceLXXueYaJi.getSN().equals("") || deviceLXXueYaJi.getDeviceId().equals("")) {
                    return failed("该用户没有绑定此设备!");
                }
            }
            String result = removeDevice(deviceLXXueYaJi.getDeviceId(), 0);
            JSONObject jsonObject1 = JSON.parseObject(result);
            int code = jsonObject1.getInteger("code");
            if (code == 200) {
                deviceLXXueYaJi.setSN(null);
                deviceLXXueYaJi.setDeviceId(null);
                deviceLXXueYaJiService.update(deviceLXXueYaJi);
                UserDevice userDevice = userDeviceService.getByUserCode(userCode);
                userDevice.setLXXueYaJi(2);
                userDeviceService.update(userDevice);
                JSONObject jsonObject2 = new JSONObject();
                return success(jsonObject2);
            } else {
                return failed(jsonObject1.getString("msg"));
            }
        } catch (Exception e) {
            insertErrorForAffair("/LeXinXueYaJi/RemoveDevice!", jsonObject, e);
            return anomalous(getExceptionMsg(e));
        }

    }


    //获取数据(别人调用我的)
    @RequestMapping(value = "GetData", method = RequestMethod.POST)
    @Transactional
    public Result GetData(@RequestBody JSONObject jsonObject) {
        try {
            String dataType = jsonObject.getString("dataType");
            Object data = jsonObject.getJSONObject("data");


            if (dataType.equals("BP")) {

                JSONObject jsonObject1 = JSON.parseObject(data.toString());
                String deviceId = jsonObject1.getString("deviceId");
                String sn = jsonObject1.getString("sn");
                Double diastolicPressure = jsonObject1.getDouble("diastolicPressure");
                Double systolicPressure = jsonObject1.getDouble("systolicPressure");
                Integer heartRate = jsonObject1.getInteger("heartRate");
                Boolean irregularHeartbeat = jsonObject1.getBoolean("irregularHeartbeat");
                Boolean movementError = jsonObject1.getBoolean("movementError");
                Integer userNo = jsonObject1.getInteger("userNo");
                Date measurementDate = new Date();
                LXXueYaJi lxXueYaJi = new LXXueYaJi();
                lxXueYaJi.setLXXueYaJiCode(UUID.randomUUID().toString());
                DeviceLXXueYaJi deviceLXXueYaJi = null;
                if (sn != null) {
                    deviceLXXueYaJi = deviceLXXueYaJiService.getBySN(sn);
                    lxXueYaJi.setUserCode(deviceLXXueYaJi.getUserCode());
                }
                if (deviceId != null) {
                    lxXueYaJi.setDeviceId(deviceId);
                }
                if (diastolicPressure != null) {
                    lxXueYaJi.setDiastolicPressure(diastolicPressure);
                }
                if (systolicPressure != null) {
                    lxXueYaJi.setSystolicPressure(systolicPressure);
                }
                if (heartRate != null) {
                    lxXueYaJi.setHeartRate(heartRate);
                }
                if (irregularHeartbeat != null) {
                    lxXueYaJi.setIrregularHeartbeat(irregularHeartbeat);
                }
                if (movementError != null) {
                    lxXueYaJi.setMovementError(movementError);
                }
                if (userNo != null || userNo.equals("")) {
                    lxXueYaJi.setUserNo(userNo);
                }
                if (measurementDate != null) {
                    lxXueYaJi.setMeasurementDate(measurementDate);
                }

                lxXueYaJiService.insert(lxXueYaJi);

                JKXueya jkXueya = new JKXueya();
                jkXueya.setJKXueyaCode(UUID.randomUUID().toString());
                jkXueya.setUserCode(deviceLXXueYaJi.getUserCode());
                jkXueya.setGaoYa(systolicPressure + "");
                jkXueya.setDiYa(diastolicPressure + "");
                jkXueya.setXinLv(heartRate + "");
                jkXueya.setFromType(1);
                jkXueya.setInspectTime(new Date());
                jkXueya.setCreateTime(new Date());
                jkXueyaService.insert(jkXueya);


            }


            Result result = new Result();
            result.setCode(200);
            result.setMsg("成功");
            return result;
        } catch (Exception e) {
            insertErrorForAffair("/LeXinXueYaJi/GetData!", jsonObject, e);
            return new Result();
        }
    }


    //获取用户血压数据返还给前端
    @RequestMapping(value = "GetDataForPage", method = RequestMethod.POST)
    public MyResult GetDataForPage(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String userCode = jsonObject.getString("userCode");
            int pageIndex =jsonObject.getInteger("pageIndex");
            int pageSize =jsonObject.getInteger("pageSize");

//            if(!checkSignPC(timeStr,sign)){
//                return failed("签名错误");
//            }
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/LeXinXueYaJi/GetDataForPage");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            PageInfo<LXXueYaJi> lxXueYaJiPageInfo =lxXueYaJiService.geyByUserCode(pageIndex,pageSize,userCode);
            return success(lxXueYaJiPageInfo);
        } catch (Exception e) {
            insertError("/LeXinXueYaJi/GetDataForPage",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }
    }

    /**
     *查询所有绑定设备的用户
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "Page",method = RequestMethod.POST)
    public MyResult GetPage(@RequestBody JSONObject jsonObject) {
        try{
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String phone = jsonObject.getString("phone");
            String sn = jsonObject.getString("sn");
            int pageIndex = jsonObject.getIntValue("pageIndex");
            int pageSize = jsonObject.getIntValue("pageSize");

            PreCheck preCheck=checkSignAdmInterface(timeStr,sign,staffCode,"/LeXinXueYaJi/Page");
            if(preCheck.getError()==1){
                return failed(preCheck.getMessage());
            }

            PageInfo<DeviceLXXueYaJiDTO> deviceLXXueYaJiDTOPageInfo = deviceLXXueYaJiService.getPage(pageIndex, pageSize, phone, sn);

            return success(deviceLXXueYaJiDTOPageInfo);
        }catch (Exception e){
            insertError("/LeXinXueYaJi/Page", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }



    public static String SHA1(String str) {
        if (StringUtils.isEmpty(str)) {
            return null;
        } else {
            return DigestUtils.sha1Hex(str);
        }

    }

    public static String ASCIISort(String str) {
        char[] test = new char[str.length()];
        StringBuilder sb = new StringBuilder();
        while (true) {
            String a = str;
            for (int i = 0; i < str.length(); i++) {
                test[i] = a.charAt(i);
            }
            Arrays.sort(test);
            for (int i = 0; i < test.length; i++) {
                sb.append(test[i]);
            }
            String trim = sb.toString().trim();
            return trim;
        }
    }


}
